package com.xin.net
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;

public class LoaderBase extends EventDispatcher
{
	protected var _url:String;
	private var _stream:URLStream;
	private var _byteArray:ByteArray;
	
	public function LoaderBase(url:String)
	{
		_url = url;
	}
	
	protected function addListeners():void 
	{
		_stream.addEventListener(Event.COMPLETE, _onComplete);
		_stream.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
		_stream.addEventListener(ProgressEvent.PROGRESS, onProgress);
		_stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
	}
	
	protected function removeListeners():void
	{
		_stream.removeEventListener(Event.COMPLETE, _onComplete);
		_stream.removeEventListener(IOErrorEvent.IO_ERROR, onIoError);
		_stream.removeEventListener(ProgressEvent.PROGRESS, onProgress);
		_stream.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
	}
	
	protected function onProgress(e:ProgressEvent):void
	{
		
	}
	
	protected function _onComplete(e:Event):void
	{
		removeListeners();
		_byteArray = new ByteArray();
		
		var length:int = _stream.bytesAvailable;
		_stream.readBytes(_byteArray, 0, length);
		_stream.close();
		
		onComplete();
	}
	
	protected function onIoError(e:IOErrorEvent):void
	{
		onError(e.text);
	}
	
	protected function onSecurityError(e:SecurityErrorEvent):void
	{
		onError(e.text);
	}
	
	/////////////////////////////////////////////
	// protected
	/////////////////////////////////////////////
	
	protected function onError(msg:String):void
	{
		var evt:ErrorEvent = new ErrorEvent(ErrorEvent.ERROR);
		evt.text = msg;
		dispatchEvent(evt);
	}
	
	protected function onComplete():void
	{
		
	}
	
	/////////////////////////////////////////////
	// public
	/////////////////////////////////////////////
	
	public function load():void
	{
		_stream = new URLStream();
		addListeners();
		_stream.load(new URLRequest(_url));
	}
	
	/**
	 * 获取加载的字节信息
	 */
	protected function getByteArray():ByteArray
	{
		return _byteArray;
	}
	
	public function get url():String
	{
		return _url;
	}
}
}